from django.conf import settings
from django.shortcuts import render

# Create your views here.
from django.views import View
from itsdangerous import TimedJSONWebSignatureSerializer, BadData
from rest_framework import mixins
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from users import serializers
from users.models import User


class TestView(View):

    def get(self, request):
        return render(request, "test.html")


class TestView2(APIView):

    def get(self, request):
        # aa = 1/0
        return Response({'message': 'get请求'})

    def post(self, request):
        return Response({'message': 'post请求'})


# 查看用户名数量接口
class UsernameCountView(APIView):
    """获取用户数量"""
    def get(self, request, username):
        """获取指定用户数量"""
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count,
        }

        return Response(data)


# 查看手机号数量接口
class MobileCountView(APIView):
    """获取手机数量"""
    def get(self, request, mobile):
        """获取手机数量"""
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count,
        }

        return Response(data)


# 用户注册接口
class CreateUserView(CreateAPIView):
    """用户注册"""
    serializer_class = serializers.CreateUserSerializer


# 个人中心接口
class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 个人邮箱
class EmailView(UpdateAPIView):
    """修改用户邮箱（修改用户的邮箱字段）"""
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailSerializer

    # 重写GenericAPIView的方法，指定要修改的是哪一条用户数据
    def get_object(self):
        return self.request.user


# 个人邮箱激活接口
class VerifyEmailView(APIView):
    """激活用户邮箱"""
    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=400)
        # 验证token
        s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires_in=60*60*24)  # 有效期1天
        try:
            data = s.loads(token)
        except BadData:
            return Response({"message": "链接信息无效"}, status=400)

        # 查询要激活用户对象
        email = data.get('email')
        user_id = data.get('user_id')
        try:
            user = User.objects.get(email=email, id=user_id)
        except User.DoesNotExist:
            return Response({"message": "激活用户不存在"}, status=400)

        # 修改用户邮箱激活状态
        user.email_active = True
        user.save()

        return Response({"message": "OK"})


# - 接口： 增删改查（查询多条地址），设置地址标题PUT， 设置默认地址PUT
class AddressViewSet(mixins.CreateModelMixin, GenericViewSet):
    """ 用户地址管理
    1. 地址增删改查（查多条）
    2. 设置默认地址: put
    3. 设置地址标题: put
    """
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        count = request.user.addresses.count()
        if count >= 5:  # 每个用户最多不能超过2个地址
            return Response({'message': '地址个数已达到上限'}, status=400)
        return super().create(request, *args, **kwargs)

    def get_queryset(self):
        # 返回当前登录用户所有的地址
        return self.request.user.addresses.filter(is_deleted=False)

    # 重写list方法
    def list(self, request, *args, **kwargs):
        """ 用户地址列表数据 """
        queryset = self.get_queryset()  # 当前登录用户的所有地址
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'user_id': request.user.id,
            'default_address_id': request.user.default_address_id,
            'limit': 5,
            'addresses': serializer.data  # 列表
        })
